<template>
  <div>
    <elm-header  :title="cateTitle">
      <template slot="left">
        <van-icon name="arrow-left" size="0.18rem" @click="$router.back()"/>
      </template>
    </elm-header>
    <!-- 下拉选择框 -->
    <van-dropdown-menu class="select-box" overlay active-color='#3190e8'>
      <!-- 商铺分类 -->
      <van-dropdown-item ref="dropCateRef"  title="分类"  @open="handleShopCateOpen">
        <div class="cate-box">
          <van-sidebar v-model="cateActiveKey" @change="handleShopCateChange">
            <van-sidebar-item v-for="cate in shopCateList" :key="cate.id">
              <!-- 分类项 -->
              <template slot="title">
                <div>
                  <img class="cate-img" :src="getImgPath(cate.image_url)" alt="">
                  <span>{{cate.name}}</span>
                </div>
                <div>
                  <van-tag round color="#cccccc">{{cate.count}}</van-tag>
                  <van-icon name="arrow" color="#cccccc"/>
                </div>
              </template>
            </van-sidebar-item>
          </van-sidebar>
          <!-- 子分类列表 -->
          <subcate-list v-if="shopCateList.length" :cateList="shopCateList[cateActiveKey].sub_categories" 
            @handleItemClick="handleSubCateClick"
          />
        </div>
      </van-dropdown-item>
      <!-- 排序 -->
      <van-dropdown-item title="排序" ref="dropSortRef">
        <div class="sort-box">
          <div class="sort-item" v-for="sortItem in sortList" :key="sortItem.title"
            @click="handleSort(sortItem.orderBy)"
          >
            <van-icon class="sort-item-icon" :name="sortItem.icon"  :color="sortItem.iconColor" size=".18rem"/>
            <div class="sort-item-right">
              <span>{{sortItem.title}}</span>
              <van-icon class="sort-selected-icon" name="success"  v-if="shopParams.order_by===sortItem.orderBy"/>
            </div>
          </div>
        </div>
      </van-dropdown-item>
      <!-- 筛选 -->
      <van-dropdown-item title="筛选" ref="dropSiftRef" @open="handleSiftOpen">
        <div class="sift-box">
          <div class="sift-content">
            <div class="sift-title">配送方式</div>
              <icon-tag-pane :list="deliveryModes"
                :useSlot="true"
                @onCheck="handleDeliverySelect">
                <svg style="width:.2rem;height:.2rem;opacity: 1;">
                  <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#fengniao"></use>
                </svg>
              </icon-tag-pane>
            <div class="sift-title">商家属性（可以多选）</div>
              <icon-tag-pane :list="shopAttrs" @onCheck="handleShopAttrSelect">
              </icon-tag-pane>
          </div>
          <div class="sift-footer">
            <van-button type="default" @click="handleSiftClear">清空</van-button>
            <van-button type="primary" @click="handleSiftConfirm">确定</van-button>
          </div>
        </div>
      </van-dropdown-item>
    </van-dropdown-menu>
    <div class="scroller" >
      <shop-list :shops="nearShopList" ></shop-list>
    </div>
  </div>
</template>
<script>
import elmHeader from '../../components/elmHeader'
import shopList from '../../components/shopList'
import subcateList from './components/subcateList'
import iconTagPane from './components/iconTagPane'
import {uniqueArray} from '../../util/util'
import {getImgPath} from '../../components/mixins'
import {
  getShops,
  getShopCates,
  getShopDeliveryModes,
  getShopActivityAttrs
 } from '../../api/restaurant'
export default {
  mixins:[getImgPath],
  components:{
    'elm-header' : elmHeader,
    'shop-list': shopList,
    'subcate-list': subcateList,
    'icon-tag-pane': iconTagPane,
  },
  created(){
    this.init()
  },
  data(){
    return{
      cateId:null,
      cateTitle:'',
      shopParams:{
        latitude:0,
        longitude:0,
        restaurant_category_id:null,
        restaurant_category_ids:[], //商铺子分类
        order_by:null, //默认4 智能匹配
        delivery_mode:[],
        support_ids:[]
      },

      // 排序分类
      sortList:[
        {icon:'back-top', iconColor:'#3b87c8', title:'智能排序', orderBy:4},
        {icon:'location-o', iconColor:'#37a1d6', title:'距离最近',orderBy:5},
        {icon:'fire-o', iconColor:'#f07373', title:'销量最高', orderBy:6},
        {icon:'gold-coin-o', iconColor:'#e6b61a', title:'起送价最低', orderBy:1},
        {icon:'clock-o', iconColor:'#37c7b7', title:'配送速度最快', orderBy:2},
        {icon:'star-o', iconColor:'#eba53b', title:'评分最高', orderBy:3}
      ],
      // 商铺分类列表
      shopCateList:[],
      // 选中的商铺分类
      cateActiveKey:0,
      deliveryModes:[],
      shopAttrs:[],
      // 附近商铺
      nearShopList:[]
    }
  },
  methods:{
    // 初始化数据
    init(){
      // 参数
      const {id,title} = this.$route.query
      this.cateId = id
      this.cateTitle = title
      let arr = this.$route.query.geohash.split(',')
      this.shopParams.latitude = parseFloat(arr[0])
      this.shopParams.longitude = parseFloat(arr[0])
      
    },
    // 获取附近商铺
    async getShopList(){
      console.log('获取商铺');
      try {
        const data = await getShops(this.shopParams)
        console.log(data);
        this.nearShopList = data
      } catch (err) {
        console.log(err);
      }
    },
    // 获取商铺分类
    async getShopCateList(){
      if(this.shopCateList.length!=0){
        return
      }
      try {
        let data = await getShopCates({
          latitude : this.latitude,
          longitude : this.longitude
        })
        // console.log(data);
        // 开发阶段：后台数据id重复，开始去重--------
        data = uniqueArray(data, 'id')
        // 结束去重---------------
        
        const index = data.findIndex(item =>{
          if(item.id === this.cateId){
            return item
          }
        })
        if(index != -1){
          this.cateActiveKey = index
        }

        this.shopCateList = data
      } catch (err) {
        console.log(err);
      }
    },
    // 获取配送方式和 商家属性
    getModesAndAttrs(){
      if(this.deliveryModes.length!=0 && this.shopAttrs.length!=0){
        return
      }
      this.$axios.all([
        getShopDeliveryModes(),
        getShopActivityAttrs()
      ]).then(this.$axios.spread((modes, attrs )=>{
        // console.log(modes);
        // console.log(attrs);
        this.deliveryModes = modes.map(item=>{
          item.checked = false
          return item
        })
        this.shopAttrs = attrs.map(item=>{
          item.checked = false
          return item
        })
      })).catch(err=>{
        console.log(err);
      })
    },
    // 分类下拉框
    handleShopCateOpen(val){
      if(!this.shopCateList.length){
        this.getShopCateList()
      }
    },
    // 改变商铺分类
    handleShopCateChange(index){
      console.log(index);
      // console.log(this.shopCateList[index]);
    },
    // 点击商铺子分类
    handleSubCateClick(subCate){
      this.cateTitle = subCate.name
      this.shopParams.restaurant_category_ids = [subCate.id]
      this.$refs.dropCateRef.toggle(false)
    },
    // 选择排序方式 
    handleSort(orderBy){
      this.shopParams.order_by = orderBy
      this.$refs.dropSortRef.toggle(false)
    },
    
    // 筛选下拉框
    handleSiftOpen(){
      this.getModesAndAttrs()
    },
    // 选择配送方式
    handleDeliverySelect( id, checked){
      for(let dm of this.deliveryModes){
        if(dm.id === id){
          dm.checked = checked
        }
      }
      if(checked){
        this.shopParams.delivery_mode.push(id)
      }else{
        this.shopParams.delivery_mode = this.shopParams.delivery_mode.filter(item=>{
          return !(item===id)
        })
      }
    },
    // 选择商铺属性
    handleShopAttrSelect( id, checked){
      for(let sa of this.shopAttrs){
        if(sa.id === id){
          sa.checked = checked
        }
      }
      if(checked){
        this.shopParams.support_ids.push(id)
      }else{
        this.shopParams.support_ids = this.shopParams.support_ids.filter(item=>{
          return !(item===id)
        })
      }
    },

    // 清空筛选列表
    handleSiftClear(){
      this.deliveryModes.forEach(item=>{
        item.checked = false
      })
      this.shopAttrs.forEach(item=>{
        item.checked = false
      })
      this.shopParams.delivery_mode = []
      this.shopParams.support_ids = []
    },
    // 确定筛选
    handleSiftConfirm(){
      this.$refs.dropSiftRef.toggle(false)
      this.getShopList()
    },
  },
  watch:{
    'shopParams.latitude':function(){
      this.getShopList()
    },
    'shopParams.longitude':function(){
      this.getShopList()
    },
    'shopParams.restaurant_category_ids':function(){
      this.getShopList()
    },
    'shopParams.order_by':function(){
      this.getShopList()
    },
  }
}
</script>
<style lang='scss' scoped>
@import '../../styles/var.scss';
.select-box{
  height: .38rem;
  width: 100%;
  position: fixed;
  top: .45rem;
  left: 0;
  z-index: 100;
  background-color: #fff;
 
  /deep/ .van-dropdown-menu__item{
    margin: 4px 0;
    border-right: 1px solid #eee;
    
  }
  /deep/ .van-dropdown-menu__bar{
    height: .38rem;
    box-shadow:none;
    border-bottom: 1px solid #eee;
    :last-child{
      border-right: none;
    }
  }
  /deep/ .van-dropdown-menu__title{
    line-height: .16rem;
    font-size: .13rem;
  }
  // 分类盒子
  .cate-box{
    display: flex;
    min-height: 3rem;
    max-height: 4rem;
    .cate-img{
      width: .19rem;
      height: .19rem;
    }
    .van-sidebar{
      width:48%;
      background-color: #f5f5f5;
      .van-sidebar-item{
        padding: .1rem .12rem;
      }
      // 取消vant 默认的红色竖线
      /deep/ .van-sidebar-item--select::before {
          content: none;
      }
      /deep/ .van-sidebar-item__text{
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #666;
        font-size: .13rem;
        *{
          vertical-align: middle;
        }
      }
    
    }
    
  }
  // 排序盒子
  .sort-box{
    .sort-item{
      height: .58rem;
      display: flex;
      align-items: center;
      .sort-item-icon{
        margin-left: .09rem;
        margin-right: .076rem;
      }
      .sort-item-right{
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: .58rem;
        line-height: .58rem;
        border-bottom: .01rem solid #eee;
        padding-right: .08rem;
        .sort-selected-icon{
          color: $primary;
        }
      }
    }
  }
  // 筛选盒子
  .sift-box{
    font-size: .13rem;
    color: #333;
    .sift-content{
      padding: 0 .1rem;
      padding-bottom: .12rem;
      .sift-title{
        font-size: .14rem;
        height: .36rem;
        line-height: .36rem;
        padding-right: .11rem;
      }
      
    }
    .sift-footer{
      display: flex;
      justify-content: space-around;
      padding: 8px 0;
      background: #f1f1f1;
      .van-button{
        width: 45%;
      }
    }
  }
}

.scroller{
  margin-top: .83rem;
}
</style>